package wpmp.portal.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import wcommons.httputils.ResponseUtils;
import wcommons.httputils.quickbean.RespInfo;
import wcommons.lang.NumberUtils;
import wpmp.extjs3.data.TreeNode;
import wpmp.portal.service.UserService;
import wpmp.security.client.internal.SecurityUtils;
import wpmp.utils.Statics;
import wpmp.utils.quickbean.UserView;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 11:49:20 AM Dec 5, 2013
 */
@Controller
@RequestMapping("/main.do")
public class MainController extends BaseController {

	static final String SUCCESS = "main";

	@Autowired
	private UserService service;

	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
	public String list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// 获取用户权限视图
		final UserView userView = this.getAndSetUserView(req);
		if (userView == null) {
			req.setAttribute("centerHtml", StringUtils.EMPTY);
			req.setAttribute("sid", SecurityUtils.getSecurityId(req));
			return SUCCESS;
		}

		// 获取center部分代码
		final StringBuilder centerHtml = new StringBuilder();
		int tbarIndex = 0;
		for (UserView.Entry entry : this.getChildren(userView, 1l)) {
			if (tbarIndex > 0) {
				centerHtml.append(",");
			}
			addToTopBar(userView, centerHtml, entry, tbarIndex++);
		}

		req.setAttribute("centerHtml", centerHtml.toString());
		req.setAttribute("sid", SecurityUtils.getSecurityId(req));
		return SUCCESS;
	}

	@RequestMapping(params = "action=listJSON", method = { RequestMethod.GET, RequestMethod.POST })
	public void listJSON(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String resourceId = req.getParameter("resourceId");
		if (StringUtils.isBlank(resourceId)) {
			String node = req.getParameter("node");
			if (StringUtils.isNotBlank(node)) {
				resourceId = node;
			}
		}

		final List<TreeNode> treeNodes = new ArrayList<TreeNode>();

		// 获取用户权限视图
		final UserView userView = this.getAndSetUserView(req);
		if (userView == null) {
			ResponseUtils.renderJson(resp, TreeNode.toJSONString(treeNodes));
			return;
		}

		final List<UserView.Entry> children = this.getChildren(userView, Long.valueOf(resourceId.trim()));
		for (UserView.Entry child : children) {
			final TreeNode node = new TreeNode();
			node.setId(child.getId().toString());
			node.setText(child.getName());
			node.setLeaf(child.getIsLeaf());
			node.addAttribute("url", child.getUrl());
			treeNodes.add(node);
		}

		final String result = TreeNode.toJSONString(treeNodes);

		if (log.isDebugEnabled()) {
			log.debug(result);
		}

		ResponseUtils.renderJson(resp, result);
	}

	private List<UserView.Entry> getChildren(UserView userView, Long resourceId) {
		final List<UserView.Entry> results = new ArrayList<UserView.Entry>();

		for (UserView.Entry entry : userView.getResources()) {
			if (NumberUtils.eq(resourceId, entry.getParentId())) {
				results.add(entry);
			}
		}

		return results;
	}

	private UserView getAndSetUserView(HttpServletRequest req) {
		final String securityId = SecurityUtils.getSecurityId(req);
		// 先从session中拿
		UserView result = this.getUserView(req, securityId);
		if (result != null) {
			return result;
		}

		final RespInfo<UserView> respInfo = service.getUserView(securityId);

		if (respInfo == null) {
			return null;
		}

		if (respInfo.isSuccess()) {
			result = respInfo.getResult();
			// 放入session中
			this.setUserView(req, result);
		}
		else {
			log.error("Failed to get UserView from AuthServer, response: " + respInfo);
		}

		return result;
	}

	private void addToTopBar(UserView userView, StringBuilder centerHtml, UserView.Entry entry, int tbarIndex)
			throws Exception {
		if (entry.getIsLeaf()) {
			centerHtml.append("\n{\n");
			centerHtml.append(" title: '").append(entry.getName()).append("',\n");
			centerHtml.append(" layout: 'fit',\n");
			centerHtml.append(" margins:'0 4 4 0',\n");
			centerHtml.append(" autoHeight: true,\n");
			centerHtml.append(" autoScroll: true,\n");
			centerHtml.append(" autoWidth: true,\n");
			centerHtml.append(" frame: false,\n");
			centerHtml.append(" html: '<iframe src=\"").append(entry.getUrl()).append("\" width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"yes\"></iframe>'\n");
			centerHtml.append("}");
			return;
		}
		centerHtml.append("\n{\n");
		centerHtml.append(" title:'").append(entry.getName()).append("',\n");
		centerHtml.append(" layout:'border',\n");
		centerHtml.append(" items:[");
		centerHtml.append("  {\n");
		centerHtml.append("   title:'功能菜单',\n");
		centerHtml.append("   region:'west',\n");
		centerHtml.append("   width:180,\n");
		centerHtml.append("   split:true,\n");
		centerHtml.append("   layout:'accordion',\n");
		centerHtml.append("   collapsible:true,\n");
		centerHtml.append("   items: [\n");

		int itemIndex = 0;
		for (UserView.Entry item : this.getChildren(userView, entry.getId())) {
			if (itemIndex > 0) {
				centerHtml.append(",");
			}
			addToItemBar(userView, centerHtml, item, tbarIndex, itemIndex++);
		}

		centerHtml.append("\n   ]\n");
		centerHtml.append("  },\n");
		centerHtml.append("  {\n");
		centerHtml.append("   region:'center',\n");
		centerHtml.append("   xtype:'panel',\n");
		centerHtml.append("   html: '<iframe name=\"centerIframe").append(tbarIndex).append("\" src=\"commons/pages/center.html\" width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"yes\"></iframe>'\n");
		centerHtml.append("  }\n");
		centerHtml.append(" ]\n");
		centerHtml.append("}");
	}

	private void addToItemBar(UserView userView, StringBuilder centerHtml, UserView.Entry resource, int tbarIndex,
			int itemIndex) throws Exception {
		centerHtml.append("\n    {\n");
		centerHtml.append("     title:'&nbsp;").append(resource.getName()).append("',\n");
		centerHtml.append("     items:[{\n");
		centerHtml.append("      xtype:'treepanel',\n");
		centerHtml.append("      style:'text-align:left',\n");
		centerHtml.append("      autoScroll:false,\n");
		centerHtml.append("      frame:false,\n");
		centerHtml.append("      enableDD:false,\n");
		centerHtml.append("      containerScroll:true,\n");
		centerHtml.append("      rootVisible:").append(resource.getIsLeaf()).append(",\n");
		centerHtml.append("      border:false,\n");
		centerHtml.append("      animate:true,\n");
		centerHtml.append("      split:true,\n");
		centerHtml.append("      root:new Ext.tree.AsyncTreeNode({\n");
		centerHtml.append("       id:'").append(resource.getId()).append("',\n");
		centerHtml.append("       text:'").append(resource.getName()).append("',\n");

		if (resource.getIsLeaf()) {
			centerHtml.append("       leaf:true,\n");
			centerHtml.append("       url:'").append(resource.getUrl()).append("'\n");
		}
		else {
			centerHtml.append("       leaf:false\n");
		}

		centerHtml.append("      }),\n");

		if (!resource.getIsLeaf()) {
			centerHtml.append("      loader:new Ext.tree.TreeLoader({\n");
			centerHtml.append("       url:(contextPath+'/main.do?action=listJSON'),\n");
			centerHtml.append("       listeners:{\n");
			centerHtml.append("        beforeload:function(thiz,node,callback){\n");
			centerHtml.append("         Ext.Msg.wait('加载数据中, 请稍后...');\n");
			centerHtml.append("        },\n");
			centerHtml.append("        load:function(thiz,node,response){\n");
			centerHtml.append("         Ext.Msg.hide();\n");
			centerHtml.append("        }\n");
			centerHtml.append("       }\n");
			centerHtml.append("      }),\n");
		}
		centerHtml.append("      listeners:{\n");
		centerHtml.append("       click:function(node,eventObject){\n");
		centerHtml.append("        var currentPosition=getCurrentPosition(node);\n");
		centerHtml.append("        var paraUrl='currentPosition='+currentPosition+'&").append(Statics.SECURITY_ID).append("='+sid;\n");
		centerHtml.append("        var linkUrl=spliceParaUrl(node.attributes.url,paraUrl);\n");
		centerHtml.append("        var centerWin=this.ownerCt.ownerCt.ownerCt.get(1);\n");
		centerHtml.append("        window.frames[\"centerIframe").append(tbarIndex).append("\"].location=linkUrl;\n");
		centerHtml.append("       }\n");
		centerHtml.append("      }\n");
		centerHtml.append("     }]\n");
		centerHtml.append("    }");
	}
}
